// pages/message-center/message-center.js
var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

var reload = true;

var SDKVersion = '';
var status = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    albumid: '',

    userInfo: '',
    uid: '',
    token: '',
    colorSet: '',
    tc: 0,
    page: 1,
    limit: 10,
    data: [],
    hasMore: true,
    hasLoadding: false,
    noData: false,
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    var titlename = tc == 1 ? '消息發布審核' : '消息发布审核';
    wx.setNavigationBarTitle({
      title: titlename,
    });
    this.setData({
      windowH: wx.getSystemInfoSync().windowHeight,
    })




    var that = this;

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('car-commerce/car-commerce', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })
    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        });
      }

    });
    //获取关于等信息
    app.getAllAbout('shouqian', function (res) {
      that.setData({
        shouqian_phone: res
      })
    });
    that.load(true);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  // getOrgVerified: function () {
  //   var that = this;

  //   var params = {
  //     publickey: util.publiccode,
  //     ac: "getOrgVerified",
  //     uid: that.data.uid,
  //     orgid: util.orgid,
  //   }
  //   util.api({
  //     data: params,
  //     success: function (responseData) {
  //       console.log("getOrgVerified：", responseData.data);

  //       var result = responseData.data;
  //       if (result.res == true) {

  //         that.getTopicList();
  //       }
  //     }
  //   });
  // },

  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return (Y + M + D)
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  reject: function (e) {
    console.log("reject选中了:", e);
    var that = this;
    console.log("reject:", e.detail.value);
    // console.log("reject:", e.currentTarget.dataset.show);
    console.log("reject:", e.currentTarget.dataset.id);
    var privatekey = utilMd5.hexMD5(that.data.uid + 'checkMessageRecently' + that.data.token);
    var params = {
      ac: "checkMessageRecently",
      uid: that.data.uid,
      verified: e.detail.value == true ? 0 : 1,
      topicid: e.currentTarget.dataset.id,
      privatekey: privatekey
    };


    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: responseData.data.msg,
            showCancel: false,
          })
        } else {
          // var contentsucess = that.data.tc == 1 ? '保存成功' : '保存成功';
          // wx.showModal({
          //   title: '提示',
          //   content: contentsucess,
          //   showCancel: false,

          // });
          that.load(true);
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });

  },

  load: function (refresh) {
    this.setData({
      hasLoadding: true,
    });
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
    });
    var dataType = this.data.topicType;
    var page = that.data.page;
    var num = that.data.limit;
    if (refresh && that.data.data.length > 0) {
      page = 1;
      num = that.data.data.length;
      that.setData({
        page: page
      })
    }
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiclist",
        orgid: util.orgid,
        topictype: 1,
        albumid: that.data.albumid,
        // toporder: 1,
        page: page,
        num: num
      },
      success: function (responseData) {
        console.log("所有数据列表：", responseData);
        var data = responseData.data;
        var newData;
        if (data && !data.msg) {
          for (var i = 0; i < data.length; i++) {
            data[i].message = app.parseHTMLText(data[i].message);
            var date = new Date(data[i].dateline * 1000);
            data[i].formattime = util.formatTime(date, '-', ':');
            //处理用户等级
            var level = 0;
            var num = data[i].user.scorenum
            data[i].user.level = 0;
            data[i].user.junfen = 0;
            if (num > 0) {
              var fen = data[i].user.scorecoin;
              var junfen = (fen / num).toFixed(1);
              if (junfen >= 4) {
                if (num >= 10000) {
                  level == 5;
                } else if (num >= 5000) {
                  level == 4;
                } else if (num >= 3000) {
                  level == 3;
                } else if (num >= 500) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              } else if (junfen >= 3) {
                if (num >= 10000) {
                  level == 4;
                } else if (num >= 5000) {
                  level == 3;
                } else if (num >= 3000) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              } else if (junfen >= 2) {
                if (num >= 10000) {
                  level == 3;
                } else if (num >= 5000) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              } else {
                if (num >= 10000) {
                  level == 2;
                } else if (num >= 100) {
                  level == 1;
                }
              }

              data[i].user.level = level;
              data[i].user.junfen = junfen;
            }
            if (that.data.latitude) {
              //计算直线距离
              var distanStr = '';
              var distan = app.getDistance(that.data.latitude, that.data.longitude, data[i].lat, data[i].lon);
              if (distan > 1000) {
                distanStr = (distan / 1000).toFixed(2) + 'km';
              } else {
                distanStr = distan.toFixed(0) + 'm';
              }
              data[i].distanse = distanStr;
            }
            //处评论者信息
            var peoples = data[i].people;
            var comments = data[i].comments;
            for (var j = 0; j < comments.length; j++) {
              var commentUserId = comments[j].author.uid;
              if (peoples.indexOf(commentUserId) >= 0) {
                commrents[j].buied = true;
              }
            }
          }
          if (refresh) {
            newData = data
          } else {
            newData = that.data.data.concat(data);
          }
          for (var i = 0; i < newData.length; i++) {

            newData[i]['post_time'] = that.toDate(newData[i]['dateline']);

          }
          console.log("=======:", newData);

          var woyaoqiuzhi = [];
          var woyaozhaopin = [];
          for (var i = 0; i < newData.length; i++) {

            if (newData[i]['albumid'] == '13') {
              woyaoqiuzhi.push(newData[i]);
            } else if (newData[i]['albumid'] == '14') {
              woyaozhaopin.push(newData[i]);
            }

          }

          that.setData({
            data: newData,
            hasLoadding: false,
            woyaoqiuzhi: woyaoqiuzhi,
            woyaozhaopin: woyaozhaopin

          });
        } else {
          that.setData({
            hasMore: false
          });
        }
        if (that.data.data.length <= 0) {
          that.setData({
            noData: true
          })
        }
        wx.hideLoading();
      }
    });


  },

  loadMore: function () {
    var page;
    if (this.data.hasMore && !this.data.hasLoadding) {
      page = this.data.page;
      this.setData({
        page: ++page
      });
      this.load(false);
    }
    console.log('load more', this.data.page)
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({ url: path });
    }
  },
})